<template>
  <div class="step-container">
    <h2 class="step-title">知识图谱生成</h2>
    <div class="content-section">
      <!-- 学科选择 -->
      <div class="subject-select-wrapper">
        <el-select
          v-model="selectedSubject"
          placeholder="请选择学科"
          class="subject-select"
        >
          <el-option
            v-for="item in subjectList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>

      <!-- 内容预览区域 -->
      <div class="content-preview">
        <h3>待解析内容预览：</h3>
        <el-input
          type="textarea"
          v-model="textContent"
          :rows="8"
          readonly
          placeholder="Step1中输入的内容将显示在这里"
        />
      </div>

      <!-- 生成进度和状态显示 -->
      <div v-if="generating" class="progress-section">
        <el-progress 
          :percentage="progress" 
          :status="progressStatus"
        />
        <p class="progress-text">{{ progressMessage }}</p>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button @click="handlePrev">上一步</el-button>
        <el-button 
          type="primary" 
          :loading="generating"
          :disabled="!canGenerate"
          @click="handleGenerate"
        >
          {{ generating ? '生成中...' : '开始生成' }}
        </el-button>
        <el-button 
          type="primary" 
          :disabled="!canProceed"
          @click="handleNext"
        >
          下一步
          <el-icon class="el-icon--right"><ArrowRight /></el-icon>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { useActiveStepIndex } from '@/stores/counter'
import { useTextContent } from '@/stores/textContent'
import { ElMessage } from 'element-plus'
import { getSubjects } from '@/api/subject'
import { generateGraphDataStream } from '@/api/ai'

const useStepIndex = useActiveStepIndex()
const textContentStore = useTextContent()

// 响应式数据
const selectedSubject = ref(null)
const subjectList = ref([])
const generating = ref(false)
const progress = ref(0)
const progressMessage = ref('')
const progressStatus = ref('') // success / exception

// 从store获取文本内容
const textContent = computed(() => {
  return textContentStore.textContent
})

// 判断是否可以生成
const canGenerate = computed(() => {
  return selectedSubject.value && textContent.value.trim().length > 0
})

// 判断是否可以进入下一步
const canProceed = computed(() => {
  return !generating.value && progress.value === 100
})

// 获取学科列表
const getSubjectList = async () => {
  try {
    const response = await getSubjects(JSON.parse(localStorage.getItem('user')).id, 1, 100)
    if (response.code === 200) {
      subjectList.value = response.data.list
    } else {
      ElMessage.error(response.message || '获取学科列表失败')
    }
  } catch (error) {
    console.error('获取学科列表失败', error)
    ElMessage.error('获取学科列表失败')
  }
}

// 处理知识图谱生成
const handleGenerate = async () => {
  if (!canGenerate.value) {
    ElMessage.warning('请先选择学科并确保有内容需要解析')
    return
  }

  generating.value = true
  progress.value = 0
  progressMessage.value = '正在开始生成...'
  progressStatus.value = ''

  try {
    const graphRequest = {
      message: textContent.value,
      subjectId: selectedSubject.value
    }

    const provider = localStorage.getItem('aiModel') || 'deepseek'
    
    // 创建EventSource
    const eventSource = await generateGraphDataStream(graphRequest, provider)
    
    // 监听消息
    eventSource.addEventListener('message', (event) => {
      try {
        const data = JSON.parse(event.data)
        
        switch (data.name) {
          case 'progress':
            progressMessage.value = data.data
            // 更新进度，假设每收到一条progress消息增加10%
            progress.value = Math.min(progress.value + 10, 90)
            break
            
          case 'complete':
            progress.value = 100
            progressStatus.value = 'success'
            progressMessage.value = data.data
            generating.value = false
            ElMessage.success('知识图谱生成完成')
            break
            
          case 'error':
            progressStatus.value = 'exception'
            progressMessage.value = data.data
            generating.value = false
            ElMessage.error(data.data)
            break
            
          case 'warning':
            ElMessage.warning(data.data)
            break
        }
      } catch (error) {
        console.error('处理消息出错:', error)
      }
    })

  } catch (error) {
    generating.value = false
    progressStatus.value = 'exception'
    progressMessage.value = '生成失败'
    ElMessage.error('生成知识图谱失败: ' + error.message)
  }
}

// 上一步
const handlePrev = () => {
  if (generating.value) {
    ElMessage.warning('正在生成中，请等待完成或刷新页面重试')
    return
  }
  useStepIndex.previousStep()
}

// 下一步
const handleNext = () => {
  if (canProceed.value) {
    useStepIndex.nextStep()
  } else {
    ElMessage.warning('请先完成知识图谱生成')
  }
}

// 组件挂载时获取学科列表
onMounted(() => {
  getSubjectList()
})
</script>

<style scoped>
.step-container {
  margin-top: 20px;
}

.step-title {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 24px;
}

.content-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 24px;
}

.subject-select-wrapper {
  margin-bottom: 20px;
}

.subject-select {
  width: 240px;
}

.content-preview {
  margin-bottom: 24px;
}

.content-preview h3 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 12px;
}

.progress-section {
  margin: 24px 0;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.progress-text {
  margin-top: 12px;
  color: #606266;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
}

:deep(.el-textarea__inner) {
  background-color: #fff;
  font-family: 'Courier New', Courier, monospace;
}
</style>